using MediatR;
using RBAC.Domain.WarehouseManagement;
using RBAC.ErrorCode;
using RBAC.Read.Api.Application.Command.ERP.PurchasingManagement.PurchaseInvoicefolder;
using Dapper;
using Microsoft.Extensions.Logging;
using RBAC.Interstructrue.Base;
using System.Linq;
using System.Collections.Generic;

namespace RBAC.Read.Api.Application.Handler.ERP.PurchasingManagement.PurchaseInvoicefolder
{
    public class GetSalesReturnDetailsCommandHandler : IRequestHandler<GetSalesReturnDetailsCommands, APIResult<APIPaging<SalesReturnDetails>>>
    {
        private readonly IBaseRepository<SalesReturnDetails> _repo;
        private readonly ILogger<GetSalesReturnDetailsCommandHandler> _logger;

        public GetSalesReturnDetailsCommandHandler(IBaseRepository<SalesReturnDetails> repo,
            ILogger<GetSalesReturnDetailsCommandHandler> logger)
        {
            _repo = repo;
            _logger = logger;
        }

        public Task<APIResult<APIPaging<SalesReturnDetails>>> Handle(GetSalesReturnDetailsCommands request, CancellationToken cancellationToken)
        {
            var res = new APIResult<APIPaging<SalesReturnDetails>>();
            var page = new APIPaging<SalesReturnDetails>();

            try
            {
                var fromSql = " FROM SalesReturnDetails srd WHERE srd.IsDeleted = 0";

                // 统计总数
                var countSql = "SELECT COUNT(1)" + fromSql;
                var total = _repo.Query<int>(countSql).FirstOrDefault();

                page.TotalCount = total;
                page.Code = APIEnums.Success;
                page.Msg = "获取销售退货明细成功";

                if (total == 0)
                {
                    page.PageDatas = new List<SalesReturnDetails>();
                    res.Code = APIEnums.Success;
                    res.Msg = page.Msg;
                    res.Data = page;
                    return Task.FromResult(res);
                }

                // 分页参数
                var pageIndex = request.PageIndex <= 0 ? 1 : request.PageIndex;
                var pageSize = request.PageSize <= 0 ? 10 : request.PageSize;
                var offset = (pageIndex - 1) * pageSize;
                if (offset < 0) offset = 0;
                var param = new DynamicParameters();
                param.Add("Offset", offset);
                param.Add("PageSize", pageSize);

                // 数据查询（选择全部列，避免因遗漏/不匹配字段导致的映射异常）
                var dataSql = @"SELECT srd.* " + fromSql + @"
                                ORDER BY srd.Id DESC
                                LIMIT @Offset, @PageSize";

                var rows = _repo.Query<SalesReturnDetails>(dataSql, param).ToList();
                page.PageDatas = rows;

                res.Code = APIEnums.Success;
                res.Msg = page.Msg;
                res.Data = page;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取销售退货明细失败: {Message}", ex.Message);
                page.Code = APIEnums.Error;
                page.Msg = "获取销售退货明细失败";
                res.Code = APIEnums.Error;
                res.Msg = page.Msg;
                res.Data = page;
            }

            return Task.FromResult(res);
        }
    }
}
